package com.dy.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dy.mapper.DishesMapper;
import com.dy.utils.JsonResultUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/dishesDeleteServlet")
public class DishesDeleteServlet extends HttpServlet {
    public DishesDeleteServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码类型
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取账号和密码
        int did = Integer.parseInt(request.getParameter("did"));

        //1. 获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2. 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取Mapper接口的代理对象
        DishesMapper dishesMapper = sqlSession.getMapper(DishesMapper.class);
        //4. 执行方法
        dishesMapper.deleteById(did);

        //提交事务
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();

        JSONObject data = JsonResultUtil.getJson("1");
        response.getWriter().print(data);
    }
}
